package fileexplorer.model;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: rejeev
 * Date: 4/27/13
 * Time: 2:01 PM
 * To change this template use Leaf | Settings | Leaf Templates.
 */
public class FileManager {
    public Directory getDirectory(String path, int level)
    {
        File file = new File(path);
        if(!file.exists()) return null;
        if(!file.isDirectory()) return null;
        if(!file.canRead()) return null;
        return getDirectory(file, level);
    }

    private Directory getDirectory(File file, int level)
    {
        Directory thisDirectory = new Directory();
        thisDirectory.name = file.getName();
        thisDirectory.path = file.getAbsolutePath();
        File[] directories = file.listFiles(new DirectoryFilter());
        if(directories == null) return thisDirectory;
        if(directories.length > 0) thisDirectory.hasChildren = true;
        if(level <= 1) return thisDirectory;
        Arrays.sort(directories);
        for(File directory : directories){
            Directory d = getDirectory(directory, level-1);
            if(d != null) thisDirectory.childDirectories.add(d);
        }
        return thisDirectory;
    }

    public File[] getFiles(String directoryPath){
        File directory = new File(directoryPath);
        if(!directory.exists()) return null;
        if(!directory.isDirectory()) return null;
        if(!directory.canRead()) return null;
        return directory.listFiles();
    }
}

class DirectoryFilter implements FileFilter{

    @Override
    public boolean accept(File file) {
        return file.isDirectory();
    }
}
